/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import controller.exceptions.NonexistentEntityException;
import controller.exceptions.PreexistingEntityException;
import controller.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import model.entity.Restaurant;
import model.entity.Orders;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import model.entity.PaymentMethod;

/**
 *
 * @author lnngu_000
 */
public class PaymentMethodJpaController implements Serializable {

    public PaymentMethodJpaController( EntityManagerFactory emf) {
        
        this.emf = emf;
    }

    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(PaymentMethod paymentMethod) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (paymentMethod.getOrdersCollection() == null) {
            paymentMethod.setOrdersCollection(new ArrayList<Orders>());
        }
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Restaurant restaurantId = paymentMethod.getRestaurantId();
            if (restaurantId != null) {
                restaurantId = em.getReference(restaurantId.getClass(), restaurantId.getRestaurantId());
                paymentMethod.setRestaurantId(restaurantId);
            }
            Collection<Orders> attachedOrdersCollection = new ArrayList<Orders>();
            for (Orders ordersCollectionOrdersToAttach : paymentMethod.getOrdersCollection()) {
                ordersCollectionOrdersToAttach = em.getReference(ordersCollectionOrdersToAttach.getClass(), ordersCollectionOrdersToAttach.getOrderId());
                attachedOrdersCollection.add(ordersCollectionOrdersToAttach);
            }
            paymentMethod.setOrdersCollection(attachedOrdersCollection);
            em.persist(paymentMethod);
            if (restaurantId != null) {
                restaurantId.getPaymentMethodCollection().add(paymentMethod);
                restaurantId = em.merge(restaurantId);
            }
            for (Orders ordersCollectionOrders : paymentMethod.getOrdersCollection()) {
                PaymentMethod oldPaymentMethodIdOfOrdersCollectionOrders = ordersCollectionOrders.getPaymentMethodId();
                ordersCollectionOrders.setPaymentMethodId(paymentMethod);
                ordersCollectionOrders = em.merge(ordersCollectionOrders);
                if (oldPaymentMethodIdOfOrdersCollectionOrders != null) {
                    oldPaymentMethodIdOfOrdersCollectionOrders.getOrdersCollection().remove(ordersCollectionOrders);
                    oldPaymentMethodIdOfOrdersCollectionOrders = em.merge(oldPaymentMethodIdOfOrdersCollectionOrders);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findPaymentMethod(paymentMethod.getPaymentMethodId()) != null) {
                throw new PreexistingEntityException("PaymentMethod " + paymentMethod + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(PaymentMethod paymentMethod) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            PaymentMethod persistentPaymentMethod = em.find(PaymentMethod.class, paymentMethod.getPaymentMethodId());
            Restaurant restaurantIdOld = persistentPaymentMethod.getRestaurantId();
            Restaurant restaurantIdNew = paymentMethod.getRestaurantId();
            Collection<Orders> ordersCollectionOld = persistentPaymentMethod.getOrdersCollection();
            Collection<Orders> ordersCollectionNew = paymentMethod.getOrdersCollection();
            if (restaurantIdNew != null) {
                restaurantIdNew = em.getReference(restaurantIdNew.getClass(), restaurantIdNew.getRestaurantId());
                paymentMethod.setRestaurantId(restaurantIdNew);
            }
            Collection<Orders> attachedOrdersCollectionNew = new ArrayList<Orders>();
            for (Orders ordersCollectionNewOrdersToAttach : ordersCollectionNew) {
                ordersCollectionNewOrdersToAttach = em.getReference(ordersCollectionNewOrdersToAttach.getClass(), ordersCollectionNewOrdersToAttach.getOrderId());
                attachedOrdersCollectionNew.add(ordersCollectionNewOrdersToAttach);
            }
            ordersCollectionNew = attachedOrdersCollectionNew;
            paymentMethod.setOrdersCollection(ordersCollectionNew);
            paymentMethod = em.merge(paymentMethod);
            if (restaurantIdOld != null && !restaurantIdOld.equals(restaurantIdNew)) {
                restaurantIdOld.getPaymentMethodCollection().remove(paymentMethod);
                restaurantIdOld = em.merge(restaurantIdOld);
            }
            if (restaurantIdNew != null && !restaurantIdNew.equals(restaurantIdOld)) {
                restaurantIdNew.getPaymentMethodCollection().add(paymentMethod);
                restaurantIdNew = em.merge(restaurantIdNew);
            }
            for (Orders ordersCollectionOldOrders : ordersCollectionOld) {
                if (!ordersCollectionNew.contains(ordersCollectionOldOrders)) {
                    ordersCollectionOldOrders.setPaymentMethodId(null);
                    ordersCollectionOldOrders = em.merge(ordersCollectionOldOrders);
                }
            }
            for (Orders ordersCollectionNewOrders : ordersCollectionNew) {
                if (!ordersCollectionOld.contains(ordersCollectionNewOrders)) {
                    PaymentMethod oldPaymentMethodIdOfOrdersCollectionNewOrders = ordersCollectionNewOrders.getPaymentMethodId();
                    ordersCollectionNewOrders.setPaymentMethodId(paymentMethod);
                    ordersCollectionNewOrders = em.merge(ordersCollectionNewOrders);
                    if (oldPaymentMethodIdOfOrdersCollectionNewOrders != null && !oldPaymentMethodIdOfOrdersCollectionNewOrders.equals(paymentMethod)) {
                        oldPaymentMethodIdOfOrdersCollectionNewOrders.getOrdersCollection().remove(ordersCollectionNewOrders);
                        oldPaymentMethodIdOfOrdersCollectionNewOrders = em.merge(oldPaymentMethodIdOfOrdersCollectionNewOrders);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = paymentMethod.getPaymentMethodId();
                if (findPaymentMethod(id) == null) {
                    throw new NonexistentEntityException("The paymentMethod with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            PaymentMethod paymentMethod;
            try {
                paymentMethod = em.getReference(PaymentMethod.class, id);
                paymentMethod.getPaymentMethodId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The paymentMethod with id " + id + " no longer exists.", enfe);
            }
            Restaurant restaurantId = paymentMethod.getRestaurantId();
            if (restaurantId != null) {
                restaurantId.getPaymentMethodCollection().remove(paymentMethod);
                restaurantId = em.merge(restaurantId);
            }
            Collection<Orders> ordersCollection = paymentMethod.getOrdersCollection();
            for (Orders ordersCollectionOrders : ordersCollection) {
                ordersCollectionOrders.setPaymentMethodId(null);
                ordersCollectionOrders = em.merge(ordersCollectionOrders);
            }
            em.remove(paymentMethod);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<PaymentMethod> findPaymentMethodEntities() {
        return findPaymentMethodEntities(true, -1, -1);
    }

    public List<PaymentMethod> findPaymentMethodEntities(int maxResults, int firstResult) {
        return findPaymentMethodEntities(false, maxResults, firstResult);
    }

    private List<PaymentMethod> findPaymentMethodEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(PaymentMethod.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public PaymentMethod findPaymentMethod(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(PaymentMethod.class, id);
        } finally {
            em.close();
        }
    }

    public int getPaymentMethodCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<PaymentMethod> rt = cq.from(PaymentMethod.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
